<template>
  <div class="page-box">
    <el-dialog
      :visible="visible"
      @update:visible="$emit('update:visible', $event)"
      fullscreen
      title="算法配置"
      :show-close="false"
      class = "previewDialog"
    >
      <el-container >
        <el-aside  width=120px class="left-widget" >

          <h3 class="text-center" style="color: white">算法组件拖拽</h3>
          <div class="components-list">
            <template>
              <div class="widget-cate"><strong> 正则表达式</strong></div>

              <draggable
                tag="ul"
                :list="regex"
                v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                :clone="deepClone">
                <template v-for="item in regex">
                  <div class="comp-box" :key="item.id">
                    {{item.name}}
                  </div>
                </template>
              </draggable>

            </template>
            <template>
              <div class="widget-cate"><strong>第三方接口</strong></div>

              <draggable
                tag="ul"
                :list="intFacList"
                v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                :clone="deepClone">
                <template v-for="item in intFacList">
                  <div class="comp-box2" :key="item.id">
                    {{item.name}}
                  </div>
                </template>
              </draggable>

            </template>
          </div>
        </el-aside>
        <el-container class="center-container" direction="vertical">

          <el-main
            ref="main"
            @click.native="currentComp={}">
            <draggable
              class="config-row"
              v-model="editForm.all"
              v-bind="{group:'people', ghostClass: 'ghost',animation: 200}"
              @add="handleWidgetAdd($event)">
              <div
                :class="['col-box', currentComp === item ? 'active' : '']"
                v-for="(item, index) in editForm.all"
                :key="item.id"
                @click.stop="handleClick(item)"
              >
                {{item.name}}
                <i v-if="currentComp === item" class="el-icon-circle-close" @click="remove(index)"></i>
              </div>
            </draggable>
          </el-main>


          <el-main class = "task-config">
            <h3 class="text-center">任务信息</h3>
            <el-form label-width="200px" ref="editForm" :model="editForm">
              <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="editForm.taskName"/>
              </el-form-item>

              <el-form-item label="数据源类型" prop="sourceType">
                <el-select size="small" v-model="editForm.sourceType" auto-complete="off"placeholder="请选择数据源类型" class="userRole"@change="lossFocus">
                  <el-option label="结构化数据源" value="结构化数据源"></el-option>
                  <el-option label="模型任务" value="模型任务" @click.native="openDialog"></el-option>

                </el-select>
              </el-form-item>


              <!--选择结构化数据源-->
              <el-form-item v-show="isShow1"  label="数据源表" prop="datasourceIds">
                <el-select v-model="editForm.sourceId" class="filter-item" placeholder="请选择数据源表" >
                  <el-option v-for="data in StructSourceData" :key="data.id" :label="data.dataTable" :value="data.id" />
                </el-select>
              </el-form-item>


              <el-form-item v-show="isShow"  label="任务">
                <el-table
                  v-model="editForm.sourceId"
                  :data="checkedData"
                  size="small"
                  highlight-current-row
                  border>
                  <el-table-column v-if ="false" prop="id" label="任务名称"/>
                  <el-table-column prop="taskName" label="任务名称"/>
                  <el-table-column prop="example" label="条件"/>
                </el-table>
                <!-- <el-button size="small" type="success" icon="el-icon-plus" @click.native="openDialog">重新添加</el-button>
               --></el-form-item>



              <el-form-item label="任务描述" prop="taskDesc">
                <el-input v-model="editForm.taskDesc"/>
              </el-form-item>



              <el-form-item  label="存储配置" prop="stioreConfigId">
                <el-select v-model="editForm.stioreConfigId" class="filter-item" placeholder="请选择存储配置" >
                  <el-option v-for="data in storeData" :key="data.id" :label="data.storeType" :value="data.id" />
                </el-select>
              </el-form-item>

            </el-form>

            <div align="center">
              <el-button @click="test()">测试</el-button>
              <el-button @click="returnDataCleanTaskPage()">取消</el-button>
              <el-button type="primary" @click="submitForm('editForm')">确定</el-button>
            </div>

          </el-main>


        </el-container>

        <!--          currentComp.algorithmType!== ''||currentComp.algorithmType!==null-->
        <div  >

          <el-aside class="widget-config-container" >
            <el-container>
              <el-main>
                <div class = edit-main v-if = "isComponentVisible" @click="hideModal">
                  <div class="edit-main-title">
                    <h3>{{currentComp.algorithmType}}</h3>
                  </div>
                  <div v-if=" currentComp.algorithmType=== '正则'">
                    <el-form >
                      <el-form-item v-if="false" label="算法ID">
                        <el-input v-model="currentComp.id"/>
                      </el-form-item>
                      <el-form-item label="算法名称">
                        <el-input v-model="currentComp.name"/>
                      </el-form-item>
                      <el-form-item label="正则代码">
                        <el-input v-model="currentComp.regular" />
                      </el-form-item>
                    </el-form>
                  </div>
                  <div v-if=" currentComp.algorithmType=== '第三方接口'">
                    <el-form >
                      <el-form-item v-if="false" label="算法ID">
                        <el-input v-model="currentComp.id"/>
                      </el-form-item>
                      <el-form-item label="算法名称">
                        <el-input v-model="currentComp.name"/>
                      </el-form-item>
                      <el-form-item label="接口url">
                        <el-input/>
                      </el-form-item>
                      <el-form-item label="请求类型">
                        <el-input/>
                      </el-form-item>
                      <el-form-item label="参数">
                        <el-input/>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </el-main>

            </el-container>

          </el-aside>
        </div>
      </el-container>

    </el-dialog>

    <el-dialog title="选择模型任务(限制选一个任务)":visible.sync="modelTask" width="50%":show-close="false">
      <el-table  :data="taskData"
                 size="small"
                 highlight-current-row
                 :row-key="rowKeys"
                 ref="Table"
                 @selection-change="handleSelectionChange"
                 border>

        <el-table-column align="center"  type="selection" :reserve-selection="true" width="60">
        </el-table-column>
        <el-table-column v-if= "false" align="center" prop="id" label="序号" width="250">
        </el-table-column>
        <el-table-column align="center" prop="taskName" label="任务名称" width="250">
        </el-table-column>
        <el-table-column align="center" prop="example" label="条件" width="350">
        </el-table-column>
      </el-table>

      <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('task')">取 消</el-button>
        <el-button type="primary" @click="onConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible1"
      width="30%">
      <span>是否继续新增任务?</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="returnDataCleanTaskPage()">取 消</el-button>
    <el-button type="primary" @click="dialogVisible1 = false">继续</el-button>

  </span>
    </el-dialog>

  </div>
</template>

<script>
  import Draggable from 'vuedraggable'
  import axios from "axios";
  import Pagination from "../../components/Pagination";
  export default {
    name: 'algo-config',
    components: {
      Draggable,
      Pagination,
    },
    props: {
      visible: {

      }
    },
    data() {
      return {
        isComponentVisible:false,
        // 是否继续添加任务
        dialogVisible1:false,
        isDisabled:false,
        storeData:[
          {
            id: 4
          },
          {
            id: 3
          }
        ],
        StoreId:[],
        isShow:false,
        isShow1:false,
        dialogVisible: false,
        modelTask:false,

        regexShow:false,
        interfaceShow:false,

        taskData:'',
        regExpList: [
          {
            id: '1',

            name: '正则表达式1'
          },
          {
            id: '2',

            name: '正则表达式2'
          },
          {
            id: '3',

            name: '正则表达式3'
          }
        ],
        intFacList: [
          {
            id: '4',
            algorithmType:'第三方接口',
            name: '接口1'
          },
          {
            id: '5',
            algorithmType:'第三方接口',
            name: '接口2'
          },
          {
            id: '6',
            algorithmType:'第三方接口',
            name: '接口3'
          }
        ],
        multipleSelection:[],

        currentComp: {},
        StructSourceData:[],
        editForm: {
          id: '',
          taskName: '',
          sourceType: '',
          taskDesc:'',
          config:'',
          status:'',
          all:'',
          sourceId:'',
          stioreConfigId:'',
          userId: localStorage.getItem('userId')
        },
        checkedData:[],
        // 请求数据参数
        formInline: {
          page: 1,
          limit: 10,
          taskName: '',
        },
        algorithmNum:'',
        algorithmData:[],
        regex:[],
        interface:[],
        tmp:[],
        // 分页
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        //
        // rules: {
        //   taskName: [
        //     { required: true, message: '请输入任务名称', trigger: 'blur' }
        //   ],
        //   sourceType: [{ required: true, message: '请选择数据源类型', trigger: 'blur' }],
        //   taskDesc: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
        //   stioreConfigId: [{ required: true, message: '请选择存储配置', trigger: 'blur' }],
        //   datasourceIds:[{required: true, message: '请选择数据源表', trigger: 'blur'}]
        // },

      }
    },

    computed: {},
    watch: {},
    //  表单验证


    created() {
      this.getAlgorithm();

      this.getStoreSource();


    },
    mounted() {

    },
    beforeDestroy() {
      // 组件销毁前移除事件监听器
      document.removeEventListener('click', this.closeModalIfClickedOutside);
    },
    methods: {
      test(){
        console.log("vj"+JSON.stringify(this.editForm))
      },
      handleClick(item) {
        this.currentComp = item;
        this.isComponentVisible = true;
        document.addEventListener('click', this.closeModalIfClickedOutside);

      },
      hideModal() {
        this.isComponentVisible = false;
        this.currentComp = {}
        // 隐藏弹窗后，移除点击事件监听器
        document.removeEventListener('click', this.closeModalIfClickedOutside);
      },
      closeModalIfClickedOutside(event) {
        // 检查点击事件的目标是否是弹窗元素或其子元素
        if (!(event.target === this.$el || event.target.parentNode === this.$el)) {
          this.hideModal();
        }
      },



      // 选择数据
      handleWidgetAdd(evt) {
        let arr = []
        const newIndex = evt.newIndex;
        const result = this.editForm.all;

        const addedWidget = evt.item._underlying_vm_

        if(result.length===1){
          this.tmp.push(addedWidget)
        }else{
          const isDuplicate = this.tmp.some(item => item.name === addedWidget.name);
          if (isDuplicate) {
            this.$message.error('不可添加相同算法组件')
            result.splice(newIndex, 1);
          }else {
            this.tmp.push(addedWidget)
          }
        }
        if (result.length > 5) {
          this.$message.error('最多可以选择5个算法组件')
          result.splice(newIndex, 1);
        }
        // 检查是否已经存在相同的对象
      },

  deepClone(obj) {

        return JSON.parse(JSON.stringify(obj))
      },
      remove(index) {

        this.editForm.all.splice(index, 1)
        this.isComponentVisible = false
      },

      // 获取算法
      getAlgorithm(){

        let url = this.$global.javaUrl+"/dataCleanAlgorithm/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            pageNum: this.formInline.page,
            pageSize:this.formInline.limit,
            //isLock: this.formInline.isLock
          }
        }

        axios.get(url, config).then(response=>{
          this.algorithmData = response.data.data.rows
          this.algorithmNum = response.data.data.records
          for(var i=0;i<this.algorithmData.length;i++){
            if(this.algorithmData[i].algorithmType == "正则"){ // TODO
              this.regex.push({id:this.algorithmData[i].id,
                name:this.algorithmData[i].algorithmName,
                regular:this.algorithmData[i].regular,
                algorithmType:this.algorithmData[i].algorithmType
              })

            }
          }
          console.log(this.algorithmData)
        })


      },
      // 获取结构化数据源信息
      getStructSource() {

        //登录
        let url = this.$global.javaUrl + "/dataSource/list"
        axios.get(url,{
          headers:
            {
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              pageNum: '1',
              pageSize:10
            }
        }).then(res=>{

          this.StructSourceData = res.data.data.rows
          console.log("33333"+res.data.data.rows[0])


        })
      },
      // 获取大模型任务数据
      getSearchPage(formInline) {
        this.logining = true
        let url = this.$global.javaUrl +"/task/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            taskName:this.formInline.taskName,
            pageNum: this.formInline.page,
            pageSize:this.formInline.limit,

          }
        }

        axios.get(url, config).then(response=>{
          this.taskData = response.data.data.rows
          this.pageparm.total = response.data.data.records
        })

      },

      //获取存储配置
      getStoreSource() {

        //登录
        let url = this.$global.javaUrl + "/DataCleaStoreConfig/list"
        axios.get(url,{
          headers:
            {
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              pageNum: this.formInline.page,
              name: "",
              pageSize:this.formInline.limit,
            }
        }).then(res=>{
          console.log(res.data)
          this.storeData = res.data.data.rows


          console.log("1======="+this.StoreId)
        })
      },

// 编辑、添加提交方法
      submitForm(editData) {

        // this.editForm.config =  JSON.stringify(this.editForm.all) // TODO
        this.editForm.config =  this.editForm.all
        this.editForm.status= '未执行'
        this.editForm.stioreConfigId =  [this.editForm.stioreConfigId]
        let config = {
          headers:
            {
              'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            }
        }

        this.$refs[editData].validate(valid => {
          if (valid) {
            console.log(this.editForm)
            // 请求方法
            axios
              .post(this.$global.javaUrl+"/dataCleanTask/saveOrUpdate",this.editForm,config)
              .then(res => {
                this.editFormVisible = false
                this.loading = false

                if (res.data.data != null) {
                  this.$message({
                    type: 'success',
                    message: "数据保存成功！"
                  })
                  this.editForm = {}
                  this.dialogVisible1 = true
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('保存失败，请稍后再试！')
              })
          } else {
            return false
          }
        })

      },

      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getSearchPage(this.formInline)
      },
      lossFocus() {
        if (this.editForm.sourceType === "结构化数据源") {
          this.isShow1 = true
          this.isShow = false
          this.modelTask = false
          this.editForm.sourceId =''
          this.getStructSource()
        } else {
          this.modelTask = true
          this.isShow1 = false
          this.editForm.sourceId =''
          this.getSearchPage(this.formInline)

        }
      },
      openDialog(){
        this.modelTask = true
        this.$refs.table.clearSelection();
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog == 'edit') {
          this.isShow1 = false

          this.isShow = false
          this.showDataDetail = false
          this.showStructDataDetail = false
          this.editFormVisible = false

        } else if (dialog == 'task') {

          this.modelTask = false
          if(this.isShow===false){
            this.editForm.sourceType=''
          }
        } else if (dialog == 'unit') {
          this.unitAccessshow = false
        }
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      clearSelection() {
        this.multipleSelection = [];
        this.$refs.Table.clearSelection();
      },
      getSelection() {

        return this.multipleSelection;
      },
      // 确定模型任务
      onConfirm() {
        const s = this.getSelection();

        if(s==0){

          this.$message({
            type: 'warning',
            message: "未选择数据,无法保存"
          })

        }else if(s.length>1)
        {
          this.$message({
            type: 'warning',
            message: "请只勾选一个任务"
          })
        }
        else{
          this.modelTask = false;
          this.isShow = true
          this.checkedData = s;
          this.editForm.sourceId= this.checkedData[0]["id"];

        }

      },
      returnDataCleanTaskPage(){
        this.currentComp = {}
        this.tmp = [],
        this.editForm = {id: '',
          taskName: '',
          sourceType: '',
          taskDesc:'',
          config:'',
          all:'',
          sourceId:'',
          stioreConfigId:'',
          userId: localStorage.getItem('userId')}
        this.isComponentVisible = false
        this.dialogVisible1 = false
        this.modelTask = false
        this.isShow = false
        this.isShow1 = false

        //this.$emit('refresh')
        this.$parent.getList();
        this.$emit('update:visible', false)
      },
      rowKeys(row) {
        return row.id
      },
    },

  }
</script>

<style>
  .text-center {
    text-align: center;
  }
  .comp-box {
    color: #666;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

    border-radius: 180px 180px 180px 180px;
    background-color: rgba(112, 243, 255, 1);
    padding: 10px;
    text-align: center;
    margin: auto;
    cursor: default;
  }
  .comp-box2 {
    color: #666;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

    border-radius: 180px 180px 180px 180px;
    background-color: #ffff00;
    padding: 10px;
    text-align: center;
    margin: auto;
    cursor: default;
  }
  .center-container{
    position: fixed;
    left:110px;
    top:0;
  }
  .config-row {
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 200px;
    width: 900px;
    line-height: 60px;
    display: flex;
    justify-content: center;
    margin: auto;
  }

  .col-box {
    width: 80px;
    height: 80px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

    border-radius: 180px 180px 180px 180px;
    background-color: rgb(255, 224, 112);
    text-align: center;
    font-size: 20px;
    vertical-align: middle; /* 垂直居中 */
    line-height: 80px; /* 与框框高度相同，确保文字垂直居中 */
    cursor: default;
    position: relative;


  >i {
    font-size: 20px;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
  }
  }
  .col-box.active {
    border-color: #66b1ff;
    color: #66b1ff;
  }
  .left-widget{
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

    border: 1px solid #ccc;
    background-color:#303133;

    position: fixed;
    left: 0;
    bottom: 7px;
    top:0;
  }

  .widget-config-container {
    width: 200px;
  }
  .edit-main{
    border: 1px solid #ccc; /* 设置边框样式 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 设置阴影效果 */
    padding: 10px; /* 根据需要设置内边距 */
    margin: 10px; /* 根据需要设置外边距 */

    width: 210px;
    height: auto;
    position: fixed;
    right: 0;
    top:9px;


  }

  .task-config {
    background-color: #D3DCE6;
    width: 900px;
    height: 400px;


    margin-left:20px;
  }
  .edit-main-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }


  .el-dialog__header {
    display: none;
  }
  .widget-cate  {
    color: white;
  }

</style>
